<?php
namespace app\index\controller;

use Jssdk\JSSDK;
use think\Controller;
use think\View;
use Wechat\TPWechat;

class Xyjgg extends Controller
{
    protected $_action;
    protected $_controller;
    protected $wechatObj;

    //获取code
    public function getcode(){
        $appId = config('wechat.appid');
        $redirect_url = 'http://jx.mgtvshop.com/index/xyjgg/index';

        $urls = urlencode($redirect_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$urls."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";

        header("location:".$url);
    }

    public function index()
    {
        if (is_weixin()) {
            $jssdk = new JSSDK(config('wechat.appid'), config('wechat.appsecret'));
            $signPackage = $jssdk->getSignPackage();
            $this->assign('signPackage', $signPackage);
        }

        $code = isset($_GET['code'])?$_GET['code']:'';

        $appId = config('wechat.appid');
        $appKey = config('wechat.appsecret');
        $wx = new \Jssdk\WXLOGIN($appId, $appKey, $code);
        //得到用户的openid(登陆用户的识别码)和Client_ids
        $openId = $wx->getOpenId();
        if($openId == null){
            header('location:http://'.$_SERVER['HTTP_HOST'].'/index/xyjgg/getcode');
            exit;
        }

        $get_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appKey";
        $res = $this->https_request($get_token_url);
        $json_obj = json_decode($res,true);

        //根据openid和access_token查询用户信息
        $access_token = $json_obj['access_token'];

        $openId = $wx->getOpenId();

        $userinfo = $wx->userinfo($access_token,$openId);

        $userinfo = json_decode($userinfo);

        $this->assign('openid',$openId);
        $this->assign('nickname',isset($userinfo->nickname)?$userinfo->nickname:'');
        $this->assign('headimgurl',isset($userinfo->headimgurl)?$userinfo->headimgurl:'');
        $this->assign('subscribe',$userinfo->subscribe);

        return view();

    }

    /**
     * CURL请求
     * @param $url
     * @return mixed|string
     */
    function https_request($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}
        curl_close($curl);
        return $data;
    }


}
